from . import *
from user.models import User
from django.shortcuts import reverse
from yyxt.utils.tokens import get_username, TIME_OUT
from django.core.cache import cache

"""
=============================================
token限制访问，同时绑定用户对象到request
=============================================
"""


class TokenMiddleware(object):
    """通过token限制访问拦截中间件"""

    def __init__(self, get_response):
        self.get_response = get_response

        # 这个中间件初始化的代码

    def __call__(self, request):
        # request到达view之前执行的代码
        allow_urls = [
            reverse('user:login'),
            reverse('user:init'),
            reverse('check:hwsign'),
            reverse('check:sign_img'),
            reverse('check:show_sign_img'),
            reverse('check:video'),
            # reverse('check:task_pdf'),
            reverse('receipt:scan'),
            reverse('receipt:scan_pdf'),
            reverse('receipt:scan_image'),
        ]  # 限制解除登陆接口
        if request.path in allow_urls:  # 两个都是str
            pass
        else:
            token = request.META.get('HTTP_AUTHORIZATION')
            if token:
                user_name = get_username(token)
                catch_token = cache.get(user_name)
                if catch_token == token:
                    # 通过并重置token缓存时间
                    cache.set(user_name, token, TIME_OUT)
                    # 绑定用户对象(user_obj)到request中
                    try:
                        user_obj = User.objects.get(user_name=user_name)
                    except:
                        user_obj = None
                    request.user_obj = user_obj
                else:
                    return restful.un_auth(message="登陆信息已过期，请重新登陆")
            else:
                return restful.un_auth(message='未检测到登陆信息，请先登陆！')
        response = self.get_response(request)

        # response到达用户浏览器之前执行的代码

        return response